package netWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class My_TcpServer{
    private ServerSocket serverSocket=null;
    /*建立一个侦听套接字,用来查找*/
    public My_TcpServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            Socket clientsocket=serverSocket.accept();
            process(clientsocket);

        }

    }
    public void process(Socket  socket){
        System.out.printf("[%s:%d] 客户端建立连接!\n", socket.getInetAddress().toString(),
               socket.getPort());
        /*处理连接*/
        try(InputStream inputStream= socket.getInputStream()) {
            try (OutputStream outputStream=socket.getOutputStream()){
                Scanner scanner=new Scanner(inputStream);
                // 循环的处理每个请求, 分别返回响应
                while (scanner.hasNext()){
                    /*处理断开的情况*/
                    String request= scanner.next();
                    String response=response(request);
                    PrintWriter printWriter=new PrintWriter(outputStream);
                    printWriter.println(response);
                    printWriter.flush();
                    System.out.printf("[%s:%d] req: %s, resp: %s\n",socket.getInetAddress().toString(),
                            socket.getPort(), request, response);

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    public String response(String str){return str;}

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
